package cn.com.ctbri.geomonitor.filter;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.identity.User;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.web.filter.OncePerRequestFilter;

import cn.com.ctbri.geomonitor.utils.SystemConstants;

/**
 * 登录过滤器
 * 
 * @author ChaoBin
 */
public class LoginFilter extends OncePerRequestFilter {
	
	private static Logger logger = Logger.getLogger(LoginFilter.class);
	
	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		// 不过滤的uri
//		String[] notFilter = new String[] {".*"};
//		".*.css$",".*.js$",".*.jpg$",".*.png$",".*.ico$",".*.jpeg$",".*.gif$",".*/fonts/.*","/commonPages/.*",
//		".*/getVerifyCode$",".*/register$",".*/login$", ".*/logout$",".*/index$",

		// 请求的uri
		String uri = request.getRequestURI();
		// 是否过滤
		boolean doFilter = false;
//		for (String s : notFilter) {
//			if (uri.matches(s)) {
//				// 如果uri中包含不过滤的uri，则不进行过滤
//				doFilter = false;
//				break;
//			}
//		}
		
		User loginedUser = (User) request.getSession().getAttribute(SystemConstants.SESSION_USER);
		
		if (false) {
			// 执行过滤
			// 从session中获取登录者实体
			if (loginedUser == null) {
				boolean isAjaxRequest = isAjaxRequest(request);
				if (isAjaxRequest) {
					response.setCharacterEncoding("UTF-8");
					response.sendError(HttpStatus.UNAUTHORIZED.value(),
							"您已经太长时间没有操作,请刷新页面");
					return;
				}
				response.sendRedirect("index");
				return;
			} else {
				// 如果session中存在登录者实体，则继续
				filterChain.doFilter(request, response);
			}
		} else {
			// 如果不执行过滤，则继续
			filterChain.doFilter(request, response);
		}
		
		if(uri.matches(".*/detail/[0-9]*$")){
			StringBuilder logB = new StringBuilder();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			logB.append("remote machine : "+request.getRemoteAddr());
			logB.append(" , the page : "+uri);
			logB.append(" , the time : "+sdf.format(new Date()));
			if(loginedUser != null) logB.append(" , the user : "+loginedUser.getLastName());
			logger.info(logB.toString());
		}
	}

	/**
	 * 判断是否为Ajax请求 <功能详细描述>
	 * 
	 * @param request
	 * @return 是true, 否false
	 * @see [类、类#方法、类#成员]
	 */
	public static boolean isAjaxRequest(HttpServletRequest request) {
		String header = request.getHeader("X-Requested-With");
		if (header != null && "XMLHttpRequest".equals(header))
			return true;
		else
			return false;
	}
}
